package neo.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import neo.model.MLog;

@Repository("mlogDao")
public class MLogDao {
	
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	public void add(MLog mlog){
		String sql="insert into t_mlog values(null,?,?,?,?)";
		jdbcTemplate.update(sql,new Object[] {
				mlog.getDevId(),
				mlog.getStat(),
				mlog.getChange(),
				mlog.getRemark()
		});
	}
	
	public void update(MLog mlog){
		String sql = "UPDATE `t_mlog` SET `stat`=?, `change`=?, `remark`=? WHERE (`id`=?)";
		jdbcTemplate.update(sql,new Object[] {
				mlog.getStat(),
				mlog.getChange(),
				mlog.getRemark(),
				
				mlog.getId()
		});
	}
	
	public void del(Integer id){
		String sql="delete from t_mlog where id=?";
		jdbcTemplate.update(sql, new Object[]{id});
	}

	public List<MLog> findByDevId(Integer devId) {
		String sql = "select * from t_mlog where devId = ? order by id desc";
		final List<MLog> mlogs=new ArrayList<MLog>();
		jdbcTemplate.query(sql, new Object[]{devId}, new RowCallbackHandler(){

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				mlogs.add(mlogMapRow(rs));
			}
			
		});
		return mlogs;
	}
	
	/**
	 * 查询对象转换POJO对象
	 * @param rs ResultSet查询对象
	 * @return 目标POJO
	 * @throws SQLException
	 */
	private MLog mlogMapRow(ResultSet rs)throws SQLException{
		MLog mlog = new MLog();
		
		mlog.setId(rs.getInt("id"));
		mlog.setDevId(rs.getInt("devId"));
		mlog.setStat(rs.getString("stat"));
		mlog.setChange(rs.getString("change"));
		mlog.setRemark(rs.getString("remark"));
		mlog.setCreateTime(rs.getString("creatTime"));
		mlog.setChangeTime(rs.getString("changeTime"));
		
		return mlog;
	}

}
